<?php

namespace App\Http\Controllers\OpenShop\Fake;

use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\Workflow\WorkflowEnum;
use App\Http\Controllers\BaseController;
use App\Models\OpenShop\Shop\OpenShopHandleExpireShopHistoryModel;
use App\Models\OpenShop\Shop\OpenShopHandleExpireShopMainModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderToCollection;
use App\Service\System\SystemNotifyService;
use App\Service\Workflow\WorkflowOrderService;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class FakeController extends BaseController
{
    public function fakeOrder(Request $request)
    {
        if (config('app.env') == 'prod' || config('app.env') == 'pre') {
            dd('生产环境禁止执行');
        }

        ini_set('memory_limit', '2048M');
        ini_set('max_execution_time', 120);

        $stepStatus = $request->get('stepStatus');
        $num = $request->get('num', 1);
        $phone = $request->get('phone', '');

        if (!in_array($stepStatus, array_keys(MissionTemplateEnum::STEP_STATUS_TEXT)) && !$stepStatus) {
            dd('错误的stepStatus');
        }

        if ($num > 5) {
            dd('单次最多执行5条记录');
        }

        dump('参数校验成功...');
        dump('正在执行生成开店订单任务......');
        dump("所属阶段:" . MissionTemplateEnum::STEP_STATUS_TEXT[$stepStatus]);
        dump('订单数量：' . $num);
        dump('=======================================================');

        $url = 'https://file.51kuafu.com/02/83/5f204cdbaf8e614eb2d84a5256459a00006635f916ddd753e141a5b9fb23.xlsx';
        $pathInfo = parse_url($url);
        $client = new Client();
        $tempData = $client->request("get", $url)->getBody()->getContents();
        $file = md5($url) . date('YmdHis', time()) . "." . implode(".", $pathInfo)[1];
        Storage::disk("public")->put($file, $tempData);
        $import = \Maatwebsite\Excel\Facades\Excel::toCollection(null, storage_path("app/public") . "/{$file}");
        Storage::disk("public")->delete($file);

        $import = $import->first()->filter(function ($item) {
            if ($item[0] === null) {
                return false;
            }

            return true;
        });

        for ($i = 1; $i < $num; $i++) {
            $import = $import->push($import->last());
        }

        $import = $import->map(function ($item, $k) use ($stepStatus, $phone) {
            if ($k == 0) {
                return $item;
            }

            $item[1] = MissionTemplateEnum::STEP_STATUS_TEXT[$stepStatus];

            if ($phone) {
                $item[4] = $phone;
            }

            return $item;
        });

        Log::info("ImportHistoryOrder import", $import->toArray());

        (new HistoryOrderToCollection)->collection($import, null);
    }

    public function sendDaily(Request $request)
    {
        $env = $request->get('env', 'qa');
        $day = $request->get('day', '');

        Artisan::call(
            "open_shop:order_sign_new_sign_daily",
            [
                'env' => $env,
                '--day' => $day
            ]
        );
    }

    public function updateNewSignDaily(Request $request)
    {
        file_get_contents('https://api.51kuafu.com/guanyuan-tools/feishu/openShop/updateSignOrder');
        return true;
    }

    public function createRenewOrder(Request $request)
    {
        if (config('app.env') == 'prod' || config('app.env') == 'pre') {
            dd('生产环境禁止执行');
        }

        $shopId = $request->get('shopId');
        $userId = $request->get('userId');
        $workflowOrder = (new WorkflowOrderService())->init(WorkflowEnum::WORKFLOW_TYPE_OPEN_SHOP_RENEW, $shopId);

        $mainProcessModel = \App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel::query()
                                                                                             ->where('shopId', $shopId)
                                                                                             ->first();

        $userContractModel = \App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel::query()->where('orderNo', $mainProcessModel->orderNo)->first();

        $type = OpenShopHandleExpireShopHistoryModel::getType($userContractModel);

        $expireShopMainModel = OpenShopHandleExpireShopMainModel::query()
                                                                ->firstOrCreate(
                                                                    [
                                                                        "orderNo"        => $userContractModel->orderNo,
                                                                        "userContractId" => $userContractModel->id,
                                                                    ],
                                                                    [
                                                                        "orderNo"           => $userContractModel->orderNo,
                                                                        "workOrderNo"       => $workflowOrder->workflowNo,
                                                                        "shopId"            => $mainProcessModel->shopId,
                                                                        "shopCode"          => $userContractModel->signOrderRel->shopCode,
                                                                        "type"              => $type,
                                                                        "contractStartTime" => $userContractModel->startTime,
                                                                        "contractEndTime"   => $userContractModel->endTime,
                                                                        "createdAt"         => time()
                                                                    ]
                                                                );

        OpenShopHandleExpireShopHistoryModel::query()->firstOrCreate(
            [
                "mainId" => $expireShopMainModel->id,
                "type"   => $type,
            ], ["createdAt" => time()]
        );

        if ($userId) {
            $url = config('webUrl.notify_web_cdn_url') . "#/pages/work-order/renewal/renewal?workflowNo={$workflowOrder->workflowNo}";

            // 向商家发送报名消息
            $notify = SystemNotifyService::save(
                false,
                "待续签 {$workflowOrder->workflowNo}",
                SystemNotifyCenterModel::NOTIFY_TYPE_3,
                SystemNotifyCenterModel::NOTIFY_TARGET_1,
                '',
                "待续签 {$workflowOrder->workflowNo}",
                $url,
                SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
                "待续签 {$workflowOrder->workflowNo}",
                '',
                SystemNotifyCenterModel::IS_POPUP_ON,
                1,
                $shopId
            );
            SystemNotifyService::recordLog($notify, '创建消息');
            SystemNotifyService::preSend($notify->id, [$userId]);
        }

        return response()->json($workflowOrder->toArray());
    }

    /**
     * 全国+省区机器人推送
     * @param Request $request
     */
    public function provincialRobotNotice(Request $request)
    {
        $env = $request->get('env', 'qa');

        Artisan::call(
            "open_shop:provincial_robot_notice",
            [
                'env' => $env,
            ]
        );
    }
}
